// pages/wiki/[slug].js
import { useRouter } from 'next/router';
import { GetStaticPaths, GetStaticProps } from 'next';
import fs from 'fs';
import path from 'path';
import matter from 'gray-matter';
import MDXLayout from '../components/MDXLayout';
import MarkdownIt from 'markdown-it';
// 创建一个 MarkdownIt 实例
const md = new MarkdownIt();


async function displayFilesRecursively(dir,parentArray,fileSlug) {
    try {
      const entries =  fs.readdirSync(dir, { withFileTypes: true });
   
      for (const entry of entries) {
        const fullPath = path.join(dir, entry.name);
   
        if (entry.isDirectory()) {
          // 如果是目录，则递归调用
          const copyArray=parentArray.slice();
          copyArray.push(entry.name);
          await displayFilesRecursively(fullPath,copyArray,fileSlug);
        } else {
          // 如果是文件，则打印文件路径
          const copyArray=parentArray.slice();
          copyArray.push(entry.name.replace(".mdx",""));
          fileSlug.push(copyArray);
        }
      }
    } catch (err) {
      console.error(`Error reading directory ${dir}:`, err);
    }
  }


export const getStaticPaths = async () => {
    const dir=path.join(path.join(process.cwd(), 'src/pages/mdx'))
    const fileSlug = [];
    await displayFilesRecursively(dir,[],fileSlug);
    // const files = fs.readdirSync(path.join(process.cwd(), 'src/pages/mdx'));
    // const paths = files.map((filename) => ({
    //     params: { slug: [filename.replace('.mdx', '')] },
    // }));
    // console.log(fileSlug);
    const paths = fileSlug.map((slugArray)=>({
        params: { slug: slugArray },
    }))
    return { paths, fallback: false };
};

export const getStaticProps = async ({ params }) => {
    console.log(params);
    const { slug } = params;
    const fileName = slug.pop();
    let fullPath = path.join(process.cwd(), 'src/pages/mdx');
    for (let dir  of slug) {
        fullPath = path.join(fullPath,dir);
    }
    fullPath= path.join(fullPath,`${fileName}.mdx`)
    // const fullPath = path.join(process.cwd(), 'src/pages/mdx', `${slug}.mdx`);
    const fileContents = fs.readFileSync(fullPath, 'utf8');
    const { data, content } = matter(fileContents);
    // 使用 markdown-it 将 Markdown 内容转换为 HTML
    const htmlContent = md.render(content);

    return {
        props: {
            source: htmlContent,
            frontMatter: data,
        },
    };
};
const MDXPage = ({ source, frontMatter }) => {
    return (
        <MDXLayout>
            <h1>{frontMatter.title}</h1>
            <div dangerouslySetInnerHTML={{ __html: source }} />
        </MDXLayout>

    );
};

export default MDXPage;